// page/component/details/details.js
const { request } = require('../../../utils/request');
Page({
  data: {
    goods: {}, // 初始化商品数据
    num: 1,
    totalNum: 0,
    hasCarts: false,
    curIndex: 0,
    show: false,
    scaleCart: false
  },

  onLoad(options) {
    const productId = options.id;
    if (productId) {
      this.fetchProductDetails(productId);
    } else {
      console.error('未获取到商品 ID');
    }
  },

  fetchProductDetails(id) {
    request({
      url: `/product/${id}`,
      method: 'GET',
      showLoading: true
    })
    .then((res) => {
      if (res.code === 2000) {
        this.setData({
          goods: res.data
        });
      } else {
        console.error('获取商品详情失败:', res.message);
      }
    })
    .catch((error) => {
      console.error('请求商品详情接口出错:', error);
    });
  },

  addCount() {
    let num = this.data.num;
    num++;
    this.setData({
      num 
    });
  },

  addToCart() {
    const { goods, num } = this.data;
    if (!goods.id) {
      console.error('商品 ID 不存在');
      return;
    }
    request({
      url: '/cart',
      method: 'POST',
      data: {
        product_id: goods.id,
        quantity: num
      },
      showLoading: true
    })
    .then((res) => {
      if (res.code === 2000) {
        wx.showToast({
          title: '加入购物车成功',
          icon: 'success'
        });
        let total = this.data.totalNum;
        this.setData({
          show: true,
          hasCarts: true,
          totalNum: num + total
        });
        setTimeout(() => {
          this.setData({
            show: false,
            scaleCart: true
          });
          setTimeout(() => {
            this.setData({
              scaleCart: false
            });
          }, 200);
        }, 300);
      } else {
        wx.showToast({
          title: '加入购物车失败',
          icon: 'none'
        });
        console.error('加入购物车失败:', res.message);
      }
    })
    .catch((error) => {
      wx.showToast({
        title: '请求出错',
        icon: 'none'
      });
      console.error('加入购物车请求出错:', error);
    });
  },

  bindTap(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      curIndex: index
    });
  }
});